package com.hsbc.manager.web.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.hsbc.entity.Admin;
import com.hsbc.entity.Permission;
import com.hsbc.entity.Role;
import com.hsbc.manager.service.AdminService;
import com.hsbc.manager.service.PermissionService;
import com.hsbc.manager.service.RoleService;

import java.util.List;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        Admin admin = (Admin)principals.getPrimaryPrincipal();
        Integer adminId = null;
        if(admin!= null) {
        	adminId = admin.getId();
        }
        List<Role> roleList = roleService.findAdminRoleList(adminId);
        for(Role role : roleList) {
            sai.addRole(role.getRole());
            List<Permission> permissionList = permissionService.findPermissionListByRoleId(role.getId());
            for(Permission permission : permissionList) {
                sai.addStringPermission(permission.getPermission());
            }
        }
        return sai;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Admin admin = adminService.findAdminByUsername(username);
        //session失效设置，现设置为30分钟后失效
        SecurityUtils.getSubject().getSession().setTimeout(3200000);
        if (admin == null) {
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin, admin.getPassword(), ByteSource.Util.bytes(admin.getCredentialsSalt()), getName());
        return authenticationInfo;
    }
}
